package com.heima.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Override
    public ResponseResult login(LoginDto dto) {
        //防止手机号和密码为空
        if (StringUtils.isBlank(dto.getPhone())){
            return ResponseResult.okResult(AppJwtUtil.getToken(0L));
        }

        //查询到user
        LambdaQueryWrapper<ApUser> apUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apUserLambdaQueryWrapper.eq(ApUser::getPhone,dto.getPhone());
        ApUser userInDb = this.getOne(apUserLambdaQueryWrapper);
        if (userInDb==null){
            return ResponseResult.errorResult(1102,"电话号码不正确");

        }

        //将查询出来的密码与穿上来的密码加盐hash进行比较
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((dto.getPassword() + userInDb.getSalt()).getBytes());
        if (userInDb.getPassword().equals(md5DigestAsHex)){
            //去除盐和密码
            userInDb.setPassword(null);
            userInDb.setSalt(null);
            //正确的话返回数据
            HashMap hashMap = new HashMap();
            hashMap.put("user",userInDb);
            //带着token
            hashMap.put("token", AppJwtUtil.getToken(Long.valueOf(userInDb.getId())));
            return ResponseResult.okResult(hashMap);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

    }
}
